package com.elitel.frame.base.service.strategy.service;

import com.elitel.frame.main.entity.vo.BaseQueryFieldVo;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class MyBatisOgnlGenerator {

    public static void main(String[] args) {
        // 模拟数据：显示字段集合
        List<String> baseShowfieldListMap = new ArrayList<>();
        baseShowfieldListMap.add("showField1");


        baseShowfieldListMap.add("showField2");

        // 模拟数据：查询字段集合
        List<BaseQueryFieldVo> baseQueryfields = new ArrayList<>();
        BaseQueryFieldVo field1 = new BaseQueryFieldVo();
        field1.setParameterCode("name");
        field1.setParameterCondition("LIKE");
//        field1.setRequiredFlag("1"); // 必填
        baseQueryfields.add(field1);


        // 表名
        String tableName = "user";

        // 生成 MyBatis 动态 SQL
        String sql = generateMyBatisOgnl(baseShowfieldListMap, baseQueryfields, tableName);
        System.out.println(sql);
    }

    /**
     * 生成 MyBatis 动态 SQL
     *
     * @param fields             显示字段集合
     * @param baseQueryfieldList 查询字段集合
     * @param tableName          表名
     * @return 生成的 MyBatis 动态 SQL
     */
    public static String generateMyBatisOgnl(List<String> fields,
                                             List<BaseQueryFieldVo> baseQueryfieldList,
                                             String tableName) {
        StringBuilder sqlBuilder = new StringBuilder();

        // 1. 构建 SELECT 部分，只查询 baseShowfieldListMap 中的字段
        sqlBuilder.append("SELECT ");
        for (int i = 0; i < fields.size(); i++) {
            if (i > 0) {
                sqlBuilder.append(", ");
            }
            sqlBuilder.append(fields.get(i));
        }
        sqlBuilder.append(" FROM ").append(tableName).append(" WHERE 1=1\n");

        // 2. 构建 WHERE 条件部分
        for (BaseQueryFieldVo field : baseQueryfieldList) {
            String fieldName = field.getParameterCode();
            String parameterCondition = field.getParameterCondition();
            int requiredFlag = Integer.parseInt(Optional.ofNullable(field.getRequiredFlag()).orElse("0"));

            // 必填字段直接生成条件
            if (requiredFlag == 1) {
                sqlBuilder.append("  AND ").append(fieldName).append(" ").append(parameterCondition).append(" #{").append(fieldName).append("}\n");
            } else {
                // 非必填字段使用 <if> 标签
                sqlBuilder.append("  <if test=\"").append(fieldName).append(" != null and ").append(fieldName).append(" != ''\">\n");
                sqlBuilder.append("    AND ").append(fieldName).append(" ").append(parameterCondition).append(" #{").append(fieldName).append("}\n");
                sqlBuilder.append("  </if>\n");
            }
        }

        return sqlBuilder.toString();
    }

}